import Vue from 'vue'
import VueRouter from 'vue-router'
import { postchecktoken } from "@/api/login.js"
Vue.use(VueRouter)

const routes = [
  // redirect重定向,路由为/时,跳转到/home
  { path: "/", redirect: "/home" },
  {
    path: "/home",
    component: () => import("@/views/Home.vue"),
    meta: {
      title: "首页",
      // controlDisplay用来控制返回按钮的显示,为true不显示
      controlDisplay: true,
      // active用来记录底部标签栏的高亮
      active: 0,
    }
  }, 
  {
    path: "/shopping",
    component: () => import("@/views/Shopping.vue"),
    meta: {
      title: "购物车",
      controlDisplay: true,
      // login用来记录当前页面是否需要登录权限,为true则需要
      login: true,
      active: 1,
    }
  },
  {
    path: "/user",
    component: () => import("@/views/User.vue"),
    meta: {
      title: "用户",
      controlDisplay: true,
      login: true,
      active: 2,
    }
  },
  {
    path: "/search",
    component: () => import("@/views/Search.vue"),
    meta: {
      title: "搜索",
    }
  },
  {
    path: "/login",
    component: () => import("@/views/Login.vue"),
    meta: {
      title: "登录",
    }
  },
  {
    path: "/taowen",
    component: () => import("@/views/Taowen.vue"),
    meta: {
      title: "淘文",
    },
  },
  {
    path: "/taowendetails",
    component: () => import("@/views/TaowenDetails.vue"),
    meta: {

    },
  },

  {
    path: "/shuma",
    component: () => import("@/views/Shuma.vue"),
    meta: {
      title: "数码电器",
    }
  },
  {
    path: "/recommenddetails",
    component: () => import("@/views/RecommendDetails.vue"),
    meta: {

    }
  },


]

const router = new VueRouter({
  base: process.env.BASE_URL,
  routes
})


// beforeEach导航前守卫
router.beforeEach(async function (to, from, next) {

  if (to.path == "/login") {
    var token = localStorage.getItem("token")
    // 用await可以获取promise里返回的数据`
    var { data } = await postchecktoken(token)
    if (data.status == 40001) {
     
      localStorage.removeItem("token")

      next()
    } else {
      next("/")
    }
    return
  }

  if (to.meta.login == true) {

    var token = localStorage.getItem("token")
    // 用await可以获取promise里返回的数据`
    var { data } = await postchecktoken(token)

    if (data.status == 40001) {

      localStorage.removeItem("token")

      next("/login")
    } else {
      next()
    }
    return
  } 
  
  next()


})

// afterEach后置钩子(后守卫)
router.afterEach((to, from) => {

})

// 用来解决路由重复点击报错
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(to) {
  return VueRouterPush.call(this, to).catch(err => err)
}


export default router
